//创新创效 发表页面
import React, {} from 'react';
import ReactNative, {
  TextInput,
  Alert,
  Switch,
  View,
  Text,
  StyleSheet,
  Platform,
  PermissionsAndroid,
  TouchableOpacity,
  ScrollView,
  Picker,
  Image,
  Keyboard,
  ProgressViewIOS,
} from 'react-native';

import Config from '../../config';
import TImageUpLoadMultiComponent from '../../components/TImageUpLoadMultiComponent';
import CommonMaskView from '../common/CommonMaskView';
import SizeUtils from '../../common/SizeUtils';
import TImage from '../../components/TImage';
import Constants from '../../common/Constants';
import CommonStyles from '../../common/CommonStyles';
import ToastUtils from '../../common/ToastUtils';
import CreateQZPostAction from '../../actions/quanzi/CreateQZPostAction';
import CommonShowPickerAction from '../../actions/common/CommonShowPickerAction';
import CommonShowViewFullScreenAction from '../../actions/common/CommonShowViewFullScreenAction';
import DataManager from '../../datas/DataManager';
import BasePage from '../common/BasePage';
import QZ_RequestQuanziListAction from '../../actions/quanzi/QZ_RequestQuanziListAction';

const CONTENT_MIN_HEIGHT = 144;

export default class QZ_WritePage extends BasePage {
  constructor(props) {
    super(props);

    this.state = {
      pageName: "WH_BasePage",
      loadComplete: false,
      authorization: 0,
      title: "",
      tag: "",
      content: "",
      anonymous: false,
      viewStatus: 1,
      contentheight: 0,
      keyboardHeight:0,
      sub_tag:this._getBorardData()?this._getBorardData().title:'请选择',
      isUploadedImage:false, //是否已经上传完图片
    }
    this._sendRequest = false;
    this.image_url = "";
    this._imageComponent = null;

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
    // this._getBorardData() = {board_id:101,title:"婚恋交友"}
  }
  componentDidMount() {
    new QZ_RequestQuanziListAction().call(this, {page:1,page_size:200,type:'picker'})
  }
  _getBorardData() {
    return this.props.pageData.routeData.boardData;
  }
  _dealEnterPage() {
    if (this._getBorardData()) {
      this.setState({
        sub_tag:this._getBorardData().title, 
      });
    }
  }
  _dealLeavePage() {
    this.setState({
      viewStatus:1,
      sub_tag:'请选择',
      isUploadedImage:false,
    })
    if(this._imageComponent) {
      this._imageComponent.reset();
    }
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  componentWillUpdate(nextProps, nextStates) {
    if(nextStates.viewStatus == 3 && this._sendRequest) {
      this._sendRequest = false;
      new CommonShowViewFullScreenAction().call(this, null);
      this._resetState();
      Alert.alert('提示','发表成功',[
          {text:'确定',onPress:()=>{this.goBack()}}
        ])
    }
    else if(nextStates.viewStatus == 4 && this._sendRequest) {
      this._sendRequest = false;
      nextStates.viewStatus = 1;
      Alert.alert('提示','发表失败',[
          {text:'确定'}
        ])
    }
    return true;
  }

  render() {
    let scrollViewHeight = SizeUtils.getWindowSize().height - Config.paddingTop - this.state.keyboardHeight;
    if(this.state.contentheight > CONTENT_MIN_HEIGHT) {
      scrollViewHeight += this.state.contentheight - CONTENT_MIN_HEIGHT;
    }
    return(
      <View style={{paddingTop: Config.paddingTop, backgroundColor:"#ffffff"}}>
        <ScrollView style={{flexDirection:"column", height:SizeUtils.getWindowSize().height - Config.paddingTop}}
            ref={(ref) => {this._scrollView = ref}}
            keyboardShouldPersistTaps={"never"}>
          <View style={{height:scrollViewHeight,}}>
            {this._renderView()}
          </View>
          <View style={{width:SizeUtils.getWindowSize().width, height:this.state.keyboardHeight,}}>
          </View>
        </ScrollView>
        {this._renderNavigationBar()}
      </View>
    )
  }

  _keyboardDidShow(e){
    if(e.endCoordinates){
         this.setState({
          keyboardHeight:e.endCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }else if(e.startCoordinates){
        this.setState({
          keyboardHeight:e.startCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }
  }

  _keyboardDidHide(e){
      this.setState({
          keyboardHeight:0
      }, ()=> {
        setTimeout(()=>{
          this._scrollView.scrollTo({y:0});
        },100);
      })
  }

  _scrollToEnd() {
    setTimeout(()=>{
      this._scrollView.scrollToEnd();
    }, 500);
  }

  _resetState() {
    this.setState({
      title: "",
      content: "",
      anonymous: false,
      avatar: null,
    })
  }

  _renderView() {
    // if(this.state.viewStatus == 1) {
      return (
        <View style={{
          paddingLeft: SizeUtils.translateDesignWidthToCode(40),
          paddingRight: SizeUtils.translateDesignWidthToCode(40),}}>
          {this._renderTitleView()}
          {this._renderTypes()}
          {this._renderImageUploadView()}
          {this._renderContent()}
          {/* {this._renderSecretView()} */}
          {this._renderStatusText()}
        </View>
      )
  }

  _renderTitleView() {
    return(
      <View style={{height: SizeUtils.translateDesignHeightToCode(130), borderColor: '#eeeeee',
        borderBottomWidth: SizeUtils.translateDesignNumToCode(3), justifyContent:"center",}}>
        <TextInput
          style={{
            padding:0,
            height: SizeUtils.translateDesignHeightToCode(70),
            // marginTop: SizeUtils.translateDesignHeightToCode(30),
            fontSize: SizeUtils.translateFontSizeToCode(32)}}
          onChangeText = {(title) => this.setState({title})}
          placeholder = "请输入标题"
          underlineColorAndroid="transparent"
          multiline = {true}
          value = {this.state.title}
         ref = 'titleRef'
        />
      </View>
    )
  }

  _renderContent() {
    return(
      <TextInput
        style={{padding:0,height: Math.max(SizeUtils.translateDesignHeightToCode(124), this.state.contentheight),
          borderColor: 'gray', borderWidth: 0,
          marginTop: SizeUtils.translateDesignHeightToCode(20),
           textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
        onChangeText = {(content) => this.setState({content})}
        placeholder = "请输入正文(10-700个字)"
        multiline = {true}
        underlineColorAndroid="transparent"
        value = {this.state.content}
        onContentSizeChange={this._onContentSizeChange.bind(this)}
        ref = 'contentRef'
        maxLength={700}
        onFocus = {this._scrollViewTo.bind(this)}
      />
    )
  }

  // _renderTypes() {
  //      return  (<View style={{height:SizeUtils.translateDesignHeightToCode(130), justifyContent:"center",
  //         borderColor: '#eeeeee',
  //         borderBottomWidth: SizeUtils.translateDesignNumToCode(3),}}>

  //         <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>
  //           版块:  { this._getBorardData().title}
  //         </Text>
  //       </View>)


  // }
        //选择分类
    _renderTypes() {
     if(Platform.OS === "ios"){
       return  (<TouchableOpacity disabled={this._getBorardData()!==undefined} style={{height:SizeUtils.translateDesignHeightToCode(90), justifyContent:"center",
           borderColor: '#eeeeee',flexDirection:"row",alignItems:"center",
           borderBottomWidth: SizeUtils.translateDesignNumToCode(3),}}
            onPress={this._onPressChooseType.bind(this)}>
          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>
            {"版块:  "}
          </Text>
          <Text style={{flex:1,fontSize:SizeUtils.translateFontSizeToCode(32),color: "#666666",}}>
            {this.state.sub_tag}
          </Text>
          {this._getBorardData()===undefined?<TImage source={require("../../../resource/images/home/arrow.png")}
            style={{marginRight:SizeUtils.translateDesignWidthToCode(30),width:19, height:38}}/>:null}
        </TouchableOpacity>)
      }
      else{
       return (
       <View style={{height:SizeUtils.translateDesignHeightToCode(90),
        borderColor: '#eeeeee',flexDirection:"row",alignItems:"center",
        marginLeft:SizeUtils.translateDesignWidthToCode(20),
        borderRightWidth: SizeUtils.translateDesignNumToCode(3),}}>
        <Text style={{textAlign:"center",alignItems:"center",fontSize:SizeUtils.translateFontSizeToCode(32)}}>
          {"版块:  "}
        </Text>
        <View style={{width:SizeUtils.translateDesignWidthToCode(300)}}>
       <Picker
            style={{backgroundColor:"#ffffff00"}}
            selectedValue={this.state.sub_tag}
            mode="dialog"
            prompt={'请选择'}
            onValueChange={(value) => this._onPickerCallback(value)}>
            {this.state.pickerArr.map((item, index) =>
              {return(
                <Picker.Item
                style={{fontSize:SizeUtils.translateFontSizeToCode(32),color:'#eeeeee'}}
                  key={index}
                  value={item}
                  label={item}
                />
              )}
            )}

          </Picker></View></View>)
        }

    }
    _onPressChooseType() {
      new CommonShowPickerAction().call(this, {pickerData:this.state.pickerArr,
       callback:this._onPickerCallback.bind(this)});
    }
   _onPickerCallback(selectedValue) {
     this.setState({
       sub_tag:selectedValue,
     });
   }

  _renderImageUploadView() {
    let width = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80);
    let height = SizeUtils.translateDesignWidthToCode(160);
    return(
      // <View style={{backgroundColor:"#333333", width:width,
        // height:height}}>
        <TImageUpLoadMultiComponent
          ref={(ref) => this._imageComponent = ref}
          style={{width:width,
              height:height, marginTop:SizeUtils.translateDesignHeightToCode(20)}}
          containerStyle={{width:width,
            height:height}}
          imageStyle={{width:160, height:160}} maxCount = {3}
          />
      // </View>
    )
  }

  _renderNavigationBarLeftButtonContent() {

     return (<View style={{flexDirection:"row", height:SizeUtils.translateDesignHeightToCode(51),
              alignItems:"center"}}>
            <Image source={require("../../../resource/images/common/Back-icon.png")}
                style={{width:SizeUtils.translateDesignWidthToCode(24),
                  height:SizeUtils.translateDesignWidthToCode(41)}}/>

          </View>
        )
  }

  _renderNavigationBarRightButtonContent() {
    return (
      <View style={{
        flexDirection: 'row',
        alignItems: 'center',
      }}>
        <Image source={require("../../../resource/images/quanzi/btn_send.png")}
          style={{width:SizeUtils.translateDesignWidthToCode(40), height:SizeUtils.translateDesignWidthToCode(40)}}/>
          <Text
            style={{
              paddingLeft:SizeUtils.translateDesignWidthToCode(10),
              fontSize: SizeUtils.translateFontSizeToCode(30)
            }}
          >发表</Text>
      </View>
    )
  }

  _scrollViewTo(e){
    // let target = e.nativeEvent.target;
    // let scrollLength = 200;
    // if (target === ReactNative.findNodeHandle(this.refs.contentRef)) {
    //   scrollLength = 300;
    // }
    // this._scrollView.scrollTo(SizeUtils.translateDesignHeightToCode(scrollLength));
　}

  _onContentSizeChange(event) {
    this.setState({contentheight: event.nativeEvent.contentSize.height + SizeUtils.translateDesignHeightToCode(80)}, ()=> {
      this._scrollToEnd();
    });
  }

  _renderStatusText() {
    if(this.state.viewStatus == 2 || this.state.viewStatus == 5) {
      let text = "";
      if(this.state.viewStatus == 2) {
        text = "发表中(上传文本)...";
      }
      else if(this.state.viewStatus == 5) {
        if(this.state.isUploadedImage == true) {
          text = "发表中...";
        }
        else {
          text = "发表中(上传图片)...";
        }
      }
      return (
        <View style={{paddingTop:SizeUtils.translateDesignHeightToCode(40)}}>
          <Text>{text}</Text>
        </View>
      )
    }


  }

  _onPressNavigationBarRightBtn() {
    if(this.state.title === ""){
       ToastUtils.show("请输入标题");
    }
    else if(this.state.sub_tag === "请选择"){
       ToastUtils.show("请选择板块");
    }

    else if(this.state.content === "" || this._strlen(this.state.content) < 10){
       ToastUtils.show("请输入内容(10-700个字)");
    }
    else if(this.state.viewStatus == 1) {
      if(this.avatarData === null){
        this._callCreatePostAction()
        return;
      }
      this.setState({
        viewStatus:5,
      })
      new CommonShowViewFullScreenAction().call(this, {component:CommonMaskView})
      this._imageComponent.doUpload(this._onUploadCallback.bind(this));
    }
  }

  _onUploadCallback(imageUrls) {
    this._callCreatePostAction(imageUrls);
    this.setState({
      isUploadedImage:true,
    })
  }

  _callCreatePostAction(imageUrls) {
    if(this._sendRequest){
      return;
    }
    new CreateQZPostAction().call(this, {content:this.state.content,
      title:this.state.title,
      image_urls:imageUrls,
      board_id:this._getBorardData()?this._getBorardData().board_id:this.state.data[this.state.pickerArr.indexOf(this.state.sub_tag)].board_id});
    this._sendRequest = true;
  }

  _strlen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) {
     var c = str.charCodeAt(i);
    //单字节加1
     if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
       len++;
     }
     else {
      len+=2;
     }
    }
    return len;
  }
}
